// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import RedpointNode from "./RedpointNode";

export default class RedpointSystem extends cc.EventTarget {
    private static _instance: RedpointSystem;
    public static getInstance(): RedpointSystem {
        return this._instance || (this._instance = new RedpointSystem());
    }

    public debug: boolean = false;
    private _config: any;
    private _root: RedpointNode;

    public init(config) {
        this._config = config;
        if (!this._root) this._root = new RedpointNode("root");
        for (let k in this._config) {
            let cfg = this._config[k];
            let nameArr = cfg.name.split("-");
            let tempNode = this._root;
            for (let i = 0; i < nameArr.length; i++) {
                let node = tempNode.find(nameArr[i]);
                if (!node) {
                    node = new RedpointNode(nameArr[i], cfg);
                    tempNode.add(node);
                }
                tempNode = node;
            }
        }
    }

    /**
     * 注册红点
     * @param name 
     * @param target 
     */
    public registerRedpoint(name: string, target: cc.Node) {
        let node = this.findRedpointNode(name);
        if (node) {
            node.setTarget(target);
        } else {
            this.debug && cc.log(RedpointSystem.name + ":红点" + name + "不存在！");
        }
    }

    /**
     * 取消红点
     * @param name 
     */
    public unregisterRedpoint(name: string) {
        let node = this.findRedpointNode(name);
        if (node) {
            node.removeTarget();
        } else {
            this.debug && cc.log(RedpointSystem.name + ":红点" + name + "不存在！");
        }
    }

    /**
     * 查找红点
     * @param name 
     * @returns 
     */
    public findRedpointNode(name: string): RedpointNode {
        let nameArr = name.split("-");
        let tempNode = this._root;
        let node: RedpointNode;
        for (let i = 0, len = nameArr.length; i < len; i++) {
            tempNode = tempNode.find(nameArr[i]);
            if (!tempNode) break;
            if (i === len - 1) {
                node = tempNode;
            }
        }
        return node;
    }
}
